package com.yxt.qmgf.minesweeper.ctrl;

import com.yxt.qmgf.common.ImageSrc;
import com.yxt.qmgf.minesweeper.model.mineScore;
import com.yxt.qmgf.minesweeper.service.FileScoreService;
import com.yxt.qmgf.minesweeper.service.GameBoard;
import com.yxt.qmgf.shop.ctrl.ShopController;
import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import de.felixroske.jfxsupport.FXMLController;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;

@FXMLController
public class mineController implements Initializable {

    private UserInfoVO vo;
    @FXML
    private BorderPane gameContainer;
    @FXML
    private Canvas gameCanvas;
    private int flagsPlaced;
    private int secondsElapsed;
    Image icon = new Image(ImageSrc.mine_logo_path);

    @FXML
    private Button backButton;

    public void setOff(UserInfoVO vo) {
        this.vo = vo;
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        // 不再自动弹出对话框，改为由按钮触发
    }

    public void showDifficultyDialog() {
        Alert dialog = new Alert(Alert.AlertType.CONFIRMATION);
        // 在创建Alert后添加这行代码
        dialog.initModality(Modality.APPLICATION_MODAL);
        Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
        stage.getIcons().add(icon);
        dialog.setTitle("选择游戏难度");
        dialog.setHeaderText("请选择游戏难度");

        ButtonType beginner = new ButtonType("初级 (9×9, 10雷)");
        ButtonType intermediate = new ButtonType("中级 (16×16, 40雷)");
        ButtonType expert = new ButtonType("高级 (23×23, 120雷)");
        ButtonType cancel = new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);

        dialog.getButtonTypes().setAll(beginner, intermediate, expert,cancel);
        // 添加窗口关闭事件处理
        stage.setOnCloseRequest(event -> {
            dialog.setResult(cancel);
        });
        Optional<ButtonType> result = dialog.showAndWait();
        result.ifPresent(buttonType -> {
            if (buttonType == beginner) {
                startNewGameWindow(9, 9, 10);
            } else if (buttonType == intermediate) {
                startNewGameWindow(16, 16, 40);
            } else if (buttonType == expert) {
                startNewGameWindow(23, 23, 120);
            }
        });
    }

    @FXML
    private void startGame() {
        showDifficultyDialog();
    }

    @FXML
    private void rule() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
        stage.getIcons().add(icon);
        alert.setTitle("扫雷游戏规则");
        alert.setContentText("基本规则:\n"+
                "游戏目标\u200C：找出所有地雷的位置，并标记出来，同时避免点击到地雷\n"+
                "格子内容\u200C：每个格子可能是地雷、数字或空白。数字表示该格子周围8个格子中地雷的数量\n"+
                "操作方式:\n"+
                "左键单击\u200C：点击格子以打开它。如果格子是数字，则显示周围地雷的数量；如果是空白，则自动递归打开相邻的空白格子\n"+
                "右键单击\u200C：在怀疑是地雷的格子上点击右键，标记为地雷（显示为小红旗）。再次点击可取消标记:\n"+
                "\u200C双击\u200C：当数字周围已标记的地雷数量等于该数字时，双击可快速打开周围未标记的格子（功能已做，但未生效）\n"+
                "胜负判定:\n"+
                "胜利条件\u200C：所有非地雷的格子被打开，且所有地雷被正确标记\n"+
                "失败条件\u200C：点击到地雷，游戏立即结束\n");
        alert.setHeight(600.0);
        alert.show();
    }

    @FXML
    private void jifen() {
        // 获取当前用户的所有积分记录
        List<mineScore> records = FileScoreService.getRecordsByUser(vo.getUsername());

        // 如果没有记录，显示提示
        if (records.isEmpty()) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
            stage.getIcons().add(icon);
            alert.setTitle("积分记录");
            alert.setHeaderText("暂无积分记录");
            alert.setContentText("您还没有任何游戏积分记录。");
            alert.showAndWait();
            return;
        }

        // 创建对话框显示记录
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
        stage.getIcons().add(icon);
        alert.setTitle("积分获取记录");
        alert.setHeaderText("用户: " + vo.getUsername() + " 的扫雷积分记录");

        // 创建表格
        TableView<mineScore> table = new TableView<>();

        // 日期时间列
        TableColumn<mineScore, String> dateCol = new TableColumn<>("日期时间");
        dateCol.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().getFormattedDate()));

        // 得分列
        TableColumn<mineScore, String> scoreCol = new TableColumn<>("得分");
        scoreCol.setCellValueFactory(cellData ->
                new SimpleStringProperty(String.valueOf(cellData.getValue().getScores())));

        // 总分列
        TableColumn<mineScore, String> scoreTal = new TableColumn<>("总积分");
        scoreTal.setCellValueFactory(cellData ->
                new SimpleStringProperty(String.valueOf(cellData.getValue().getScore())));

        table.getColumns().addAll(dateCol, scoreCol,scoreTal);
        table.setItems(FXCollections.observableArrayList(records));

        // 设置对话框内容
        ScrollPane scrollPane = new ScrollPane(table);
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefViewportHeight(300);

        alert.getDialogPane().setContent(scrollPane);
        alert.getDialogPane().setPrefSize(400, 350);
        alert.showAndWait();
    }

    @FXML
    private void buy() {
        try {
            // 加载购买页面的FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/shop/Shop.fxml"));
            Parent root = loader.load();

            // 获取购买页面的控制器实例
            ShopController shopController = loader.getController();

            // 创建新的Stage并设置Scene
            Stage stage = new Stage();
            stage.setTitle("购买页面");
            stage.setScene(new Scene(root));
            // 如果需要模态展示，可添加以下代码
            stage.initModality(Modality.APPLICATION_MODAL);

            // 展示购买页面
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void back() {
        Window window = backButton.getScene().getWindow();
        if (window instanceof Stage) {
            ((Stage) window).close();
        }
    }

    private MenuBar createMenuBar() {
        MenuBar menuBar = new MenuBar();
        Menu gameMenu = new Menu("游戏");

        Menu difficultyMenu = new Menu("难度");
        MenuItem beginner = new MenuItem("初级 (9×9, 10雷)");
        MenuItem intermediate = new MenuItem("中级 (16×16, 40雷)");
        MenuItem expert = new MenuItem("高级 (23×23, 120雷)");

        beginner.setOnAction(e -> startNewGameWindow(9, 9, 10));
        intermediate.setOnAction(e -> startNewGameWindow(16, 16, 40));
        expert.setOnAction(e -> startNewGameWindow(23, 23, 120));

        difficultyMenu.getItems().addAll(beginner, intermediate, expert);

        MenuItem newGame = new MenuItem("新游戏");
        MenuItem exit = new MenuItem("退出");

        newGame.setOnAction(e -> showDifficultyDialog());
        exit.setOnAction(e -> {
            Stage currentStage = (Stage) gameContainer.getScene().getWindow();
            currentStage.close();
        });

        gameMenu.getItems().addAll(newGame, difficultyMenu, new SeparatorMenuItem(), exit);
        menuBar.getMenus().add(gameMenu);

        return menuBar;
    }

    private void startNewGameWindow(int rows, int cols, int mines) {
        try {
            Stage newGameStage = new Stage();
            newGameStage.getIcons().add(icon);
            GameBoard newGameBoard = new GameBoard(rows, cols, mines,vo);

            BorderPane newRoot = new BorderPane();
            newRoot.setTop(createMenuBar());
            newRoot.setCenter(newGameBoard.createBoard());

            Scene scene = new Scene(newRoot);

            // 让窗口自动调整大小
            newGameStage.sizeToScene();
            newGameStage.setScene(scene);
            newGameStage.setTitle(String.format("扫雷游戏 - %dx%d (%d雷)", rows, cols, mines));

            // 设置最小尺寸限制
            newGameStage.setMinWidth(300);
            newGameStage.setMinHeight(300);

            newGameBoard.setCurrentStage(newGameStage);
            newGameStage.show();
            newGameStage.centerOnScreen();
        } catch (Exception e) {
            showDifficultyDialog();
        }
    }

}